package servlets;

import beans.Employee;
import service.EmployeeService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private EmployeeService employeeService = new EmployeeService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        System.out.println("EmployeeServlet收到POST请求，action=" + action);

        if ("add".equals(action)) {
            handleAddEmployee(request, response);
        } else if ("update".equals(action)) {
            handleUpdateEmployee(request, response);
        } else if ("changePassword".equals(action)) {
            handleChangePassword(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未知操作");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        System.out.println("EmployeeServlet收到GET请求，action=" + action);

        if ("get".equals(action)) {
            handleGetEmployee(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未知操作");
        }
    }

    private void handleAddEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Employee employee = new Employee();
            employee.setEmployeeName(request.getParameter("employeeName"));
            employee.setPassword(request.getParameter("password"));
            employee.setDepartmentID(Integer.parseInt(request.getParameter("departmentID")));
            employee.setPosition(request.getParameter("position"));
            employee.setEmail(request.getParameter("email"));
            employee.setPhoneNumber(request.getParameter("phoneNumber"));

            // 处理入职日期
            String hireDateStr = request.getParameter("hireDate");
            if (hireDateStr != null && !hireDateStr.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date hireDate = sdf.parse(hireDateStr);
                employee.setHireDate(hireDate);
            }

            employee.setGender(request.getParameter("gender"));

            int result = employeeService.addEmployee(employee);
            if (result > 0) {
                String message = URLEncoder.encode("员工信息添加成功", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
            } else {
                String message = URLEncoder.encode("员工信息添加失败", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
            }
        } catch (ParseException e) {
            String message = URLEncoder.encode("日期格式错误", "UTF-8");
            response.sendRedirect("geren.jsp?message=" + message);
        }
    }

    private void handleUpdateEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 从session获取当前用户信息（使用您现有的登录系统）
            HttpSession session = request.getSession();
            Employee currentUser = (Employee) session.getAttribute("user");

            if (currentUser == null) {
                response.sendRedirect("login.jsp");
                return;
            }

            // 获取要更新的员工ID
            int employeeID = Integer.parseInt(request.getParameter("employeeID"));

            // 确保用户只能修改自己的信息
            if (currentUser.getEmployeeID() != employeeID) {
                String message = URLEncoder.encode("您只能修改自己的信息", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
                return;
            }

            // 获取当前员工的完整信息
            Employee currentEmployee = employeeService.getEmployeeByID(employeeID);

            if (currentEmployee == null) {
                String message = URLEncoder.encode("未找到员工信息", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
                return;
            }

            // 更新员工信息
            Employee employee = new Employee();
            employee.setEmployeeID(employeeID);

            // 设置不可修改的字段为原值
            employee.setEmployeeName(currentEmployee.getEmployeeName());
            employee.setDepartmentID(currentEmployee.getDepartmentID());
            employee.setPosition(currentEmployee.getPosition());
            employee.setGender(currentEmployee.getGender());
            employee.setHireDate(currentEmployee.getHireDate());

            // 设置可修改的字段为新值
            employee.setPassword(request.getParameter("password"));
            employee.setEmail(request.getParameter("email"));
            employee.setPhoneNumber(request.getParameter("phoneNumber"));

            int result = employeeService.updateEmployee(employee);
            if (result > 0) {
                // 更新成功，更新session中的用户信息
                Employee updatedEmployee = employeeService.getEmployeeByID(employeeID);
                session.setAttribute("user", updatedEmployee);

                String message = URLEncoder.encode("个人信息更新成功", "UTF-8");
                response.sendRedirect("geren.jsp?refresh=true&message=" + message);
            } else {
                String message = URLEncoder.encode("个人信息更新失败", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
            }
        } catch (Exception e) {
            System.out.println("更新员工信息时出错: " + e.getMessage());
            e.printStackTrace();
            String message = URLEncoder.encode("系统错误：" + e.getMessage(), "UTF-8");
            response.sendRedirect("geren.jsp?message=" + message);
        }
    }

    private void handleGetEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int employeeID = Integer.parseInt(request.getParameter("employeeID"));
            Employee employee = employeeService.getEmployeeByID(employeeID);

            if (employee != null) {
                // 将员工信息存储到请求属性中
                request.setAttribute("employee", employee);
                request.getRequestDispatcher("geren.jsp").forward(request, response);
            } else {
                String message = URLEncoder.encode("未找到员工信息", "UTF-8");
                response.sendRedirect("geren.jsp?message=" + message);
            }
        } catch (Exception e) {
            String message = URLEncoder.encode("系统错误：" + e.getMessage(), "UTF-8");
            response.sendRedirect("geren.jsp?message=" + message);
        }
    }

    private void handleChangePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        Employee currentUser = (Employee) session.getAttribute("user");
        int employeeId = currentUser.getEmployeeID();

        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        if (oldPassword == null || oldPassword.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty() ||
            confirmPassword == null || confirmPassword.trim().isEmpty()) {
            request.setAttribute("error", "所有密码字段都不能为空");
            request.getRequestDispatcher("/pirt/driversBig/My_Account.jsp").forward(request, response);
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的新密码不一致");
            request.getRequestDispatcher("/pirt/driversBig/My_Account.jsp").forward(request, response);
            return;
        }

        try {
            boolean success = employeeService.changePassword(employeeId, oldPassword, newPassword);

            if (success) {
                request.setAttribute("message", "密码修改成功");
                session.invalidate();
                response.sendRedirect(request.getContextPath() + "/login.jsp?message=" + URLEncoder.encode("密码修改成功，请重新登录", "UTF-8"));
            } else {
                request.setAttribute("error", "原密码不正确或修改失败");
                request.getRequestDispatcher("/pirt/driversBig/My_Account.jsp").forward(request, response);
            }
        } catch (Exception e) {
            System.out.println("处理修改密码请求时出错: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("error", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/pirt/driversBig/My_Account.jsp").forward(request, response);
        }
    }
}